<template>
    <div>
        <a-row :gutter="[10,10]" style="margin-top: 10px;">
            <a-col span="24">
                <a-card size="default" title="单个机械工作时长统计">
                    <a-row>
                        <a-col span="24">
                            <a-range-picker
                                show-time
                                :ranges="{ '今天': [moment().startOf('day'), moment()], '本月': [moment().startOf('month'), moment()] }"
                                v-model="searchDateRange" size="small" style="margin-left: 6px"/>

                            <a-select :filter-option="filterOption"
                                      allowClear
                                      placeholder="请选择工地"
                                      show-search
                                      size="small"
                                      style="width: 116px;margin:0 4px 0 4px;"
                                      @change="(value)=>{selectIndex=value;getMachineInfoByArea();}">
                                <a-select-option v-for="(item,index) in buildingSites" :key="index">
                                    {{ item }}
                                </a-select-option>
                            </a-select>

                            <a-select :filter-option="filterOption"
                                      allowClear
                                      placeholder="电子标签编号"
                                      show-search
                                      size="small"
                                      style="width: 130px"
                                      @change="(value)=>{selectMachineIndex=value;getAllBuildingSitePmInfo()}">
                                <a-select-option v-for="(item,index) in mecnos" :key="index"
                                                 placeholder="请选择环保编码">
                                    {{ item }}
                                </a-select-option>
                            </a-select>

                            <a-button size="small" style="margin-left: 6px" type="primary"
                                      @click="getAllBuildingSitePmInfo">统计
                            </a-button>
                        </a-col>
                    </a-row>

                    <v-chart :option="leftOption" autoresize class="chart"/>
                </a-card>

            </a-col>
        </a-row>
    </div>
</template>

<script>
import {use} from 'echarts/core';
import VChart, {THEME_KEY} from 'vue-echarts';
import {PieChart} from 'echarts/charts';
import {BarChart} from 'echarts/charts';
import {LineChart} from 'echarts/charts';


import {
    GridComponent,
    ToolboxComponent,
    TitleComponent,
    TooltipComponent,
    LegendComponent,
} from 'echarts/components';

import {CanvasRenderer} from 'echarts/renderers';
import {ref} from 'vue';
import {METHOD, request, RESPONSE} from "../../utils/request";
import moment from "moment";
import {getNodeFromTreeByLevel} from "../../utils/util";
import {mapGetters} from "vuex";

use([
    GridComponent,
    CanvasRenderer,
    PieChart,
    BarChart,
    TitleComponent,
    TooltipComponent,
    ToolboxComponent,
    LegendComponent,
    LineChart
]);

export default {
    name: "TimeHistory",
    computed: {
        ...mapGetters('account', ['user', 'rememberMe']),
    },
    components: {
        VChart,
    },
    provide: {
        [THEME_KEY]: 'dark',
    },
    data() {
        return {
            moment,
            data: [],
            searchDateRange: [],
            rightSearchDateRange: [],
            buildingSites: [],   // 工地名字列表
            buildingSiteKeys: [],   // 工地key列表
            mecnos: [],  // 机械环保编号列表
            gdname: null, // 需要查询工地的名字
            selectIndex: null, // 选中的工地下标,初始值必须为null,因为ant控件清空之后就是null
            selectMachineIndex: -1, // 选中的机械下标
        }
    },
    setup() {
        const leftOption = ref({
            color: [],
            textStyle: {
                color: '#fff',
            },
            title: {
                text: '',
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            toolbox: {
                show: true,
                feature: {
                    saveAsImage: {
                        title: '保存为图片',
                        show: true,
                        excludeComponents: ['toolbox'],
                        pixelRatio: 2
                    }
                }
            },
            tooltip: {
                trigger: 'axis',
                // 自定义悬浮提示框内容（数据处理后加单位）
                formatter(params) { // params的个数等于折线的条数（对多条折线数据进行加单位，就需要遍历）
                    var relVal = ''
                    for (var i = 0, l = params.length; i < l; i++) {
                        // circle变量是在数据前画一个对应颜色的圆形
                        let circle = `<i class="iconfont icon-yuan" style="margin-right:4px;font-size:14px;color:${params[i].color}">o</i>`


                        if (params[i].value != null) {
                            // 除了第一行，后面都要换行
                            if (i !== 0) {
                                relVal += '<br/>';
                            }

                            relVal += circle + params[i].seriesName + params[0].name + '分';
                        }
                        // else {
                        //     relVal += circle + params[i].seriesName + params[0].name + '分';
                        // }

                    }
                    return relVal
                }
            },
            legend: {
                data: ['Direct', 'Email', 'Ad Networks', 'Video Ads', 'Search Engines'],
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: [],
                axisLabel: {
                    interval: 'auto',
                    rotate: 0,
                    width: 20,
                    align: 'right',
                    // 使用函数模板，函数参数分别为刻度数值（类目），刻度的索引
                    formatter: function (value, index) {

                        if (index === 0) {
                            console.log(index + '---' + value);
                            return '{a|' + value + '}';
                        } else {
                            console.log(index + '---' + value);

                            return value;
                        }
                    },
                    rich: {
                        a: {
                            align: 'center',   // 需要width和align一同使用才会看到效果
                        },
                    }
                }
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    fontSize: 14
                }
            },
            series: [
                {
                    name: 'test',
                    type: 'line',
                    data: [1, 100, 200],
                },
            ],
        });

        return {leftOption};
    },
    mounted() {
        this.userID = JSON.parse(localStorage.getItem(process.env.VUE_APP_USER_KEY)).id;

        //  清空原来的x轴坐标
        for (let i = 0; i < 60; i++) {
            this.leftOption.xAxis.data.push(i);
        }


        request("/areas/getAreas?id=" + this.userID, METHOD.GET).then(result => {
            if (result.data.code === 1) {

                getNodeFromTreeByLevel(result.data.data, 3, this.data);

                this.data.forEach(item => {
                    this.buildingSites.push(item.title)
                    this.buildingSiteKeys.push(item.key)
                })

                this.$message.success('成功');
            }
        });
    },
    methods: {
        getMachineInfoByArea() {
            request("/position/getDzbqByqy", METHOD.GET, {
                id: this.userID,
                sel_level: 3,
                sel_key: this.buildingSiteKeys[this.selectIndex]
            }).then(res => {
                if (res.data.code === RESPONSE.SUCCESS_CODE) {
                    this.mecnos = res.data.data;
                } else {
                    this.$message.error(res.data.msg);
                }
            })
        },
        filterOption(input, option) {
            return (
                // 过滤忽略大小写
                option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
            );
        },
        findAreaByKey(area, key) {

            if (area.children != null && area.children.length > 0) {
                // 有子节点查询所有的子节点
                for (let i = 0; i < area.children.length; i++) {
                    let result = this.findAreaByKey(area.children[i], key);
                    if (result != null) {
                        // 找到了直接返回结果
                        return result;
                    }
                }
            }

            // 没有子节点 或者子节点查完了，检查本身节点
            if (area.key === key) {
                // 找到了直接返回结果
                return area;
            } else {
                // 告诉父节点没找到，继续找
                return null;
            }

        },

        getAllBuildingSitePmInfo() {
            if (this.searchDateRange === null || this.searchDateRange.length !== 2) {
                this.$message.info("必须选择一个时间段才能查询数据")
                return;
            }
            request("/wkhr/getTbwk", METHOD.GET, {
                userid: this.userID,
                startime: this.searchDateRange.length === 2 ? parseInt(moment(this.searchDateRange[0]).valueOf() / 1000) : null,
                endtime: this.searchDateRange.length === 2 ? parseInt(moment(this.searchDateRange[1]).valueOf() / 1000) : null,
                input: this.mecnos[this.selectMachineIndex],
            }).then(res => {
                if (res.data.code === RESPONSE.SUCCESS_CODE) {

                    console.log(this.user.zwr);
                    if (this.user.zwr) {
                        // 现在在重污染区域
                        this.leftOption.backgroundColor = "#8f8800"
                        // 所有的color为红色
                        this.leftOption.color = [];
                        for (let i = 0; i < 24; i++) {
                            this.leftOption.color.push("#ff0000");
                        }
                    } else {
                        this.leftOption.backgroundColor = "#100c2a"
                        // color清空
                        this.leftOption.color = [];
                    }

                    //  清空原来的折线图数据
                    this.leftOption.series.length = 0;
                    //  清空原来线的控制图标
                    this.leftOption.legend.data.length = 0;

                    // 拿到返回数据所有的key，这些key就是折线图的name
                    for (let i = 0; i < res.data.data.length; i++) {

                        let lineName = null;
                        let lastNotNullIndex = -1;
                        let linkGap = 10; // 需要连接的空格
                        for (let j = 0; j < res.data.data[i].length; j++) {


                            if (res.data.data[i][j] != null) {

                                if (j - lastNotNullIndex > 1 && j - lastNotNullIndex <= linkGap) {
                                    // 需要把null补成值
                                    for (let k = lastNotNullIndex + 1; k < j; k++) {
                                        res.data.data[i][k] = res.data.data[i][j];
                                    }
                                }

                                // 更新遇到的不为空的下标
                                lastNotNullIndex = j;

                                if (lineName == null) {
                                    lineName = res.data.data[i][j] + '点';
                                    this.leftOption.legend.data.push(lineName);
                                }
                            }
                        }

                        // 添加一条线
                        this.leftOption.series.push({
                            name: lineName,
                            type: 'line',                         // 当前数据，按照折线图渲染
                            data: res.data.data[i],
                        });

                    }
                } else {
                    this.$message.error(res.data.msg);
                }
            })
        }
    }
}
</script>

<style scoped>
.chart {
    margin-top: 10px;
    height: 60vh;
}
</style>
